package com.xieyong.mywebsite.controller;

import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.model.dto.Result;
import com.xieyong.mywebsite.model.entity.User;
import com.xieyong.mywebsite.service.UserService;
import com.xieyong.mywebsite.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<String> register(@Pattern(regexp = "^\\S{4,16}$") String username,
                                   @Pattern(regexp = "^\\S{4,16}$") String password) {
        userService.register(username,password);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{4,16}$") String username,
                                @Pattern(regexp = "^\\S{4,16}$") String password) {
        return Result.success(userService.login(username,password));
    }

    @PostMapping("")
    public Result<String> add(@RequestBody @Validated(User.Add.class) User user) { // @RequestBody 接收前端传来的 json参数
        userService.add(user);
        return Result.success();
    }

    @PutMapping("")
    public Result<User> update(@RequestBody @Validated(User.Update.class) User user) { // @RequestBody 接收前端传来的 json参数
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/update-avatar")
    public Result<User> updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/update-password")
    public Result<User> updatePassword(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
        userService.updatePassword(params,token);
        return Result.success();
    }


    @DeleteMapping("/{id}")
    public Result<User> delete(@PathVariable Integer id) { // @PathVariable 接收前端传来的 路径参数
        userService.deleteById(id);
        return Result.success();
    }

    @DeleteMapping("/delete-batch")
    public Result<User> deleteBatch(@RequestBody List<Integer> ids) { //  @RequestBody 接收前端传来的 json参数
        userService.deleteBatch(ids);
        return Result.success();
    }

    @GetMapping("/user-info")
    public Result<User> userInfo() {
//        获取当前登录用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = map.get("username").toString();
        return Result.success(userService.findByUserName(username));
    }
    @GetMapping("/all-users")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAll();
        return Result.success(users);
    }

    @GetMapping()
    public Result<List<User>> getAll() {
        List<User> users = userService.getAllByRole("USER");
        return Result.success(users);
    }

    @GetMapping("/{id}")
    public Result<User> getOne(@PathVariable Integer id) {
        User user = userService.findById(id);
        return Result.success(user);
    }

    /**
     *
     * @param pageNum  当前页码
     * @param pageSize  每页个数
     * @return
     */

    @GetMapping("/page")
    public Result<PageInfo<User>> selectPage(
                        @RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        User user) {
        PageInfo<User> userPageInfo = userService.getPage(pageNum, pageSize,user);
        return Result.success(userPageInfo);
    }

    @PostMapping("/export")
    public void exportData(HttpServletResponse response, @RequestBody(required = false) List<User> userList) throws Exception {
        if (userList == null || userList.isEmpty()) {
            userService.exportAll(response, "USER");
        } else {
            userService.exportBatch(response, userList,"USER");
        }
    }

    @PostMapping("/import")
    public Result<File> importData(MultipartFile file) throws Exception {
        return userService.importData(file);
    }
}
